package com.hlf.modules.h5.interceptor;


import com.hlf.common.exception.BusinessException;
import com.hlf.modules.h5.annotation.AuthIgnore;
import com.hlf.modules.sys.entity.SysUserTokenEntity;
import com.hlf.modules.sys.service.SysUserTokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:38
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    //    private TokenService tokenService;
    @Autowired
    private SysUserTokenService sysUserTokenService;

    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        AuthIgnore annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
        } else {
            return true;
        }

        //如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }

        //token为空
        if (StringUtils.isBlank(token)) {
            throw new BusinessException("token不能为空");
        }

        //查询token信息
        SysUserTokenEntity sysUserTokenEntity = sysUserTokenService.queryByToken(token);

        if (sysUserTokenEntity == null || sysUserTokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new BusinessException("token失效，请重新登录");
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(LOGIN_USER_KEY, sysUserTokenEntity.getUserId());

        return true;
    }
}
